package client;

import java.net.Socket;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PrintWriter;
import java.net.Socket;


public class TcpIPClient implements NetworkClient{
	private Properties properties;
	private Socket serverSocket;
	PipedInputStream pis;
	Pinger pinger;
	BufferedReader fileterdStreamReader;
	PrintWriter outputStreamWriter;
	public TcpIPClient(){
		properties = new Properties("configs/client/client_conf.xml");
	}
	public TcpIPClient(String filepath){
		properties = new Properties(filepath);
	}
	public void setPropertiesFile(String file){
		properties = new Properties(file);
	}
	@Override
	public void setProperties(Properties properties) {
		this.properties = properties;	
	}
	
	public void establishConnection() {
		try {
			serverSocket = new Socket(properties.getProperty("server_url"),
					Integer.parseInt(properties.getProperty("port")));
			pis = new PipedInputStream();
			pinger = new Pinger(serverSocket, pis);
			Thread pingerThread = new Thread(pinger);
			pingerThread.setDaemon(true);
			fileterdStreamReader = new BufferedReader(new InputStreamReader(pis));
			pingerThread.start();
			outputStreamWriter = new PrintWriter(serverSocket.getOutputStream(), true);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public String sendWithAnswer(String strToSend) {
		String resLine = "error";
		try {
				outputStreamWriter.println(strToSend);
				resLine = fileterdStreamReader.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return resLine;
	}
}
